package com.weacar.activity;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.weacar.R;
import com.weacar.adapter.SortAdapter;
import com.weacar.bean.BannerBean;
import com.weacar.bean.BaseBean;
import com.weacar.bean.BrandBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.CharacterParser;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.PinyinComparator;
import com.weacar.utils.ToastUtil;
import com.weacar.view.GlideImageLoader;
import com.weacar.view.MySideBar;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 品牌选择器
 */
public class BrandSelectActivity extends BaseActivity {

    @BindView(R.id.lv_brand)
    ListView lv_brand;
    @BindView(R.id.sb_bar)
    MySideBar sb_bar;


    //汉字转换成拼音的类
    private CharacterParser characterParser;

    public List<BrandBean.MsgBean> mSortList;

    private SortAdapter sortAdapter;

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_all_brand)
    public void allBrand() {
        Intent intent = new Intent();
        intent.putExtra("result", "不限品牌");
        setResult(3, intent);
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_brand_select);
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        characterParser = CharacterParser.getInstance();
        // initTestData();
        initData();
    }


    public void initData() {
        getAllBrand();
    }

    /**
     * 获取所有汽车品牌
     */
    public void getAllBrand() {
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }
        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_all_brand);
        LogUtils.d("all_brand_url = " + params.getUri());
        showLoading("数据加载中...");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("all_brand_result = " + result);
                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean != null && baseBean.getCode() == 1) {
                    try {
                        BrandBean brandBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), BrandBean.class);
                        mSortList = filledData(brandBean.getMsg());
                        Collections.sort(mSortList, new PinyinComparator());
                        sortAdapter = new SortAdapter(BrandSelectActivity.this, mSortList);
                        lv_brand.setAdapter(sortAdapter);
                        // 去除不存在的索引
                        setIndex();
                        sb_bar.setOnTouchListener(new MySideBar.OnTouchListener() {
                            @Override
                            public void onTouching(char c) {
                                boolean b = false;
                                // LogUtil.showLargeLog("index = " + c);
                                for (int i = 0; i < mSortList.size(); i++) {
                                    if (String.valueOf(c).equals(mSortList.get(i).getSortLetters())) {
                                        // 定位到该条数据
                                        lv_brand.setSelection(i);
                                        b = true;
                                        break;
                                    }
                                }
                                if (!b) {
                                    Toast.makeText(getApplicationContext(), "该索引下没有数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                        lv_brand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                // ToastUtil.showShort(getApplicationContext(), "你点击了" + mSortList.get(position).getName());
                                Intent intent = new Intent();
                                intent.putExtra("result", mSortList.get(position).getName());
                                intent.putExtra("brand_id", mSortList.get(position).getId());
                                setResult(3, intent);
                                finish();

                            }
                        });


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


                closeLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeLoading();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeLoading();
            }

            @Override
            public void onFinished() {
                closeLoading();
            }
        });
    }


    private List<BrandBean.MsgBean> filledData(List<BrandBean.MsgBean> empList) {
        List<BrandBean.MsgBean> mSortList = new ArrayList<>();
        for (int i = 0; i < empList.size(); i++) {
            BrandBean.MsgBean sortModel = empList.get(i);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(empList.get(i).getName());
            // LogUtil.showLargeLog("pinyin = " + pinyin);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]") || sortString.matches("[0-9]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
                // LogUtil.showLargeLog("toUpperCase() = " + sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    /**
     * 设置索引列表
     */
    public void setIndex() {
        List<String> listindex = new ArrayList<>();
        for (int i = 0; i < mSortList.size(); i++) {
            if (!listindex.contains(mSortList.get(i).getSortLetters())) {
                listindex.add(mSortList.get(i).getSortLetters());
            }
        }

        if (listindex.size() < 1) {
            return;
        }

        sb_bar.index = new String[listindex.size()];
        for (int i = 0; i < listindex.size(); i++) {
            sb_bar.index[i] = listindex.get(i);
        }
        sb_bar.invalidate();
    }
}
